import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

class ListNode {
    int val;
    ListNode next = null;
    public ListNode(int val) {
        this.val = val;
    }
}
public class Solution2 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param lists ListNode类ArrayList
     * @return ListNode类
     */
    public ListNode mergeKLists (ArrayList<ListNode> lists) {
        // write code here
        int k = lists.size();
        ListNode ret = new ListNode(0);//带头结点
        for (int i = 0; i < k; i++) {
            ret = mergeTwoLists(ret.next, lists.get(i));
        }
        return ret.next;
    }

    public ListNode mergeTwoLists(ListNode head1, ListNode head2) {
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        ListNode newHead = new ListNode(0);//带头结点
        ListNode curN = newHead;
        while (cur1 != null && cur2 != null) {
            if (cur1.val < cur2.val) {
                curN.next = cur1;
                curN = curN.next;
                cur1 = cur1.next;
            } else {
                curN.next = cur2;
                curN = curN.next;
                cur2 = cur2.next;
            }
        }
        if(cur1 != null) {
            curN.next = cur1;
        }
        if(cur2 != null) {
            curN.next = cur2;
        }
        return newHead;
    }
}